﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EvinceUI.JQueryDataTable.Model;
using EvincePayroll.Data;
using EvincePayroll.Utility;
using EvinceUI;
using System.Text;
using System.Configuration;
using System.IO;

namespace EvincePayroll.Controllers
{
    public class EmployeeRegistrationController : Controller
    {
        //
        // GET: /EmployeeRegistration/
        string userEmailId = ConfigurationManager.AppSettings["LoginID"].ToString();
        public ActionResult Registeration()
        {
            string[] gender=new string[]{"Male","Female"};
            ViewBag.Gender = gender;
            return View();
        }

        
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Registeration(EmployeeData empData, HttpPostedFileBase profileImage, string date, string month, string year)
        {
            
            
            
            EmployeeData employee=(EmployeeData)Session["EmployeeData"];
            EvincePayrollService accountService = new EvincePayrollService(ServiceTypes.Account);
            bool result = accountService.CheckExistingUser(empData.Email);
            if (result == true)
            {
                if (profileImage != null && profileImage.ContentLength > 0)
                {
                    // extract only the fielname
                    var fileName = Path.GetFileName(profileImage.FileName);
                    // store the file inside ~/App_Data/uploads folder
                    var path = Path.Combine(Server.MapPath("~/img/Employee"), fileName);
                    profileImage.SaveAs(path);
                    empData.Image1 = profileImage.FileName;
                    empData.DateOfBirth = date + "/" + month + "/" + year;
                    empData.IsActive = 0;
                }
                List<EmployeeData> list = accountService.RegisterEmployee(empData, userEmailId);
                ViewBag.Success = "Success";
                ViewBag.Message = "Registered Successfully.";
            }
            else {
                ViewBag.Message = "User with this email ID is already exist.";
            }
            string[] gender = new string[] { "Male", "Female" };
            ViewBag.Gender = gender;

            return View();
            
        }

        [Authorize.SessionExpire]
        public ActionResult EmployeeTable()
        {
           
            return View();
        }

        public ActionResult updateEmployeeTable(string EmployeeId, int IsActive, string UserRoleId)
        {
            EmployeeData employee = (EmployeeData)Session["EmployeeData"];
            Guid employeeId = new Guid(EmployeeId);
            Guid roleId=new Guid (UserRoleId);
            EvincePayrollService employeeService = new EvincePayrollService(ServiceTypes.Employee);
            var list = employeeService.updateEmployee(employeeId,IsActive,roleId,employee.Email);
            return Json(new { Result = "Success" }, JsonRequestBehavior.AllowGet);
        }

        [Authorize.SessionExpire]
        public ActionResult AjaxEmployeeList(JQueryDataTableParamModel param)
        {
            List<EmployeeData> employeeList;

            EmployeeData employee = (EmployeeData)Session["EmployeeData"];
            EvincePayrollService employeeService = new EvincePayrollService(ServiceTypes.Employee);
            employeeList = employeeService.GetEmployeeListForActivation(userEmailId);
            if (employeeList != null)
            {


                IEnumerable<EmployeeData> filteredEmployee;

                //Check whether the companies should be filtered by keyword
                if (!string.IsNullOrEmpty(param.sSearch))
                {
                    //Used if particular columns are filtered

                    var FirstNameFilter = Convert.ToString(Request["sSearch_0"]);
                    var LastNameFilter = Convert.ToString(Request["sSearch_1"]);
                    var EmailIdFilter = Convert.ToString(Request["sSearch_2"]);
                    var CityFilter = Convert.ToString(Request["sSearch_3"]);
                    var ContactFilter = Convert.ToString(Request["sSearch_4"]);
                    var EmployeeIdFilter = Convert.ToString(Request["sSearch_5"]);
                    var RoleFilter = Convert.ToString(Request["sSearch_6"]);



                    //Optionally check whether the columns are searchable at all

                    var isFirstNameSearchable = Convert.ToBoolean(Request["bSearchable_0"]);
                    var isLastNameSearchable = Convert.ToBoolean(Request["bSearchable_1"]);
                    var isEmailSearchable = Convert.ToBoolean(Request["bSearchable_2"]);
                    var isCitySearchable = Convert.ToBoolean(Request["bSearchable_3"]);
                    var isContactSearchable = Convert.ToBoolean(Request["bSearchable_4"]);
                    var isEmployeeIdSearchable = Convert.ToBoolean(Request["bSearchable_5"]);
                    var isRoleSearchable = Convert.ToBoolean(Request["bSearchable_6"]);



                    char[] chars = new char[] { '&', '|' };

                    if (param.sSearch.IndexOfAny(chars) > 0)
                    {
                        string expression = GetExpression(param.sSearch.ToUpper());
                        StringBuilder filter = new StringBuilder();
                        filter.Append("(").Append(expression.Replace("[FIELD]", "FirstName.ToUpper()")).Append(") ||");
                        filter.Append("(").Append(expression.Replace("[FIELD]", "LastName.ToString().ToUpper()")).Append(")||");
                        filter.Append("(").Append(expression.Replace("[FIELD]", "Email.ToString().ToUpper()")).Append(")");
                        filter.Append("(").Append(expression.Replace("[FIELD]", "City.ToString().ToUpper()")).Append(") ||");
                        filter.Append("(").Append(expression.Replace("[FIELD]", "ContactNumber1.ToString().ToUpper()")).Append(")||");
                        filter.Append("(").Append(expression.Replace("[FIELD]", "EmployeeId.ToString().ToUpper()")).Append(")");
                        filter.Append("(").Append(expression.Replace("[FIELD]", "Role.ToString().ToUpper()")).Append(")");
                        filteredEmployee = employeeList;
                    }
                    else
                    {

                        filteredEmployee = employeeList
                        .Where(d => isFirstNameSearchable && d.FirstName.ToLower().Contains(param.sSearch.Trim().ToLower())
                        ||
                        isLastNameSearchable && d.LastName.ToString().ToLower().Contains(param.sSearch.Trim().ToLower())
                        ||
                        isEmailSearchable && d.Email.ToString().ToLower().Contains(param.sSearch.Trim().ToLower())
                        ||
                        isCitySearchable && d.City.ToString().ToLower().Contains(param.sSearch.Trim().ToLower())
                        ||
                        isContactSearchable && d.ContactNumber1.ToString().ToLower().Contains(param.sSearch.Trim().ToLower())
                        ||
                        isEmployeeIdSearchable && d.EmployeeId.ToString().ToLower().Contains(param.sSearch.Trim().ToLower())
                         ||
                        isRoleSearchable && d.UserRoleString.ToString().ToLower().Contains(param.sSearch.Trim().ToLower())
                        );
                    }
                }
                else
                {
                    filteredEmployee = employeeList;

                }

                var isFirstName = Convert.ToBoolean(Request["bSortable_0"]);
                var isLastName = Convert.ToBoolean(Request["bSortable_1"]);
                var isEmail = Convert.ToBoolean(Request["bSortable_2"]);
                var isCity = Convert.ToBoolean(Request["bSortable_3"]);
                var isContact = Convert.ToBoolean(Request["bSortable_4"]);
                var isEmployeeId = Convert.ToBoolean(Request["bSortable_5"]);
                var isRole = Convert.ToBoolean(Request["bSortable_6"]);

                var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
                Func<EmployeeData, string> orderingFunction = (d => sortColumnIndex == 1 && isFirstName ? d.FirstName.ToString() :
                sortColumnIndex == 2 && isLastName ? d.LastName.ToString() :
                sortColumnIndex == 3 && isEmail ? d.Email.ToString() :
                sortColumnIndex == 4 && isCity ? d.City.ToString() :
                sortColumnIndex == 5 && isContact ? d.ContactNumber1.ToString() :
                sortColumnIndex == 6 && isEmployeeId ? d.EmployeeId.ToString() :
                sortColumnIndex == 7 && isRole ? d.UserRoleString.ToString() :
                "");

                var sortDirection = Request["sSortDir_0"]; // asc or desc
                if (sortDirection == "asc")
                    filteredEmployee = filteredEmployee.OrderBy(orderingFunction);
                else
                    filteredEmployee = filteredEmployee.OrderByDescending(orderingFunction);

                var displayedEmployee = filteredEmployee.Skip(param.iDisplayStart).Take(param.iDisplayLength);


                var result = from p in displayedEmployee
                             select new[] { p.FirstName, p.LastName, p.Email, p.City, p.ContactNumber1, p.EmployeeId,p.UserRoleString, getUserRole(p.ID.ToString()), IsActive(p.ID.ToString(),p.IsActive,p.Email) };
                return Json(new
                {
                    sEcho = param.sEcho,
                    iTotalRecords = employeeList.Count(),
                    iTotalDisplayRecords = filteredEmployee.Count(),
                    aaData = result
                },
                JsonRequestBehavior.AllowGet);
            }
            else
                return Json(new { }, JsonRequestBehavior.AllowGet);
        }

        public string getUserRole(string employeeId)
        {
            List<UserRoleData> userRoleList = null;
            EmployeeData employee = (EmployeeData)Session["EmployeeData"];
            EvincePayrollService userRoleService = new EvincePayrollService(ServiceTypes.UserRole);
            userRoleList = userRoleService.GetUserRoleList(userEmailId);

            string str = "<select id=\"userRole-" + employeeId + "\" class=\"rolename\">";
            foreach (var i in userRoleList)
            {
                if (i.UserRole == "NA")
                    str += "<option selected value=\"" + i.UserRoleId + "\">" + i.UserRole + "</option>";
                else
                    str += "<option value=\""+i.UserRoleId+"\">"+i.UserRole+"</option>";
            }
            str += "</select>";
            return str;
        }
        public string IsActive(string employeeId,int isActive, string emailId)
        {
            string str = string.Empty;
            if (isActive == 0)
            {
                str = string.Format("<button class=\"btn btn-small\"onclick=\"UpdateRole(this,'{0}')\">Activate</button><a href=\"../Account/GetUserProfile?email={1}\">   View</a>", employeeId,emailId);
            }
            else if (isActive == 1)
            {
                str = string.Format("<button class=\"btn btn-small\" style=\"background-color: green;border-color: green;\" onclick=\"UpdateRoleExistingUser(this,'{0}')\">Submit</button><a href=\"../Account/GetUserProfile?email={1}&flag=1\">   View</a>", employeeId, emailId);
            }
            return str;
        }
        private string GetExpression(string p)
        {
            throw new NotImplementedException();
        }

    }
}
